
package hk.ces.oxfam.patch.sql;

import hk.ces.oxfam.patch.util.StringUtil;

/**
 *
 * @author ReutyCheng
 */
public class PreparedSQL
{
  private String sql;
  private Object[] params;

  public PreparedSQL(String sql, Object[] params)
  {
    this.sql = sql;
    this.params = params;
  }

  public Object[] getParams()
  {
    return params;
  }

  public String getSql()
  {
    return sql;
  }

  public void migrate(String flag, PreparedSQL prepareSQL)
  {
    if (!sql.contains(flag) || StringUtil.count(sql, flag) != 1)
    {
      throw new IllegalArgumentException("Prepare SQL[" + this.toString() + "] doesn't contain flag[" + flag + "]");
    }
    
    String redefinedSql = sql.replaceFirst(flag, prepareSQL.getSql());

    int redefinedParamsCount = params.length + prepareSQL.getParams().length;
    Object[] redefinedParams = new Object[redefinedParamsCount];

    char questionMark = '?';
    String[] sqlFragment = sql.split(flag);
    int countQuestionMarkInFrontSql = StringUtil.count(sqlFragment[0], questionMark);
    int countQuestionMarkInEndSql = StringUtil.count(sqlFragment[1], questionMark);

    int redefinedParamIndex = 0;

    for (int index = 0; index < countQuestionMarkInFrontSql; index++)
    {
      redefinedParams[redefinedParamIndex++] = params[index];
    }
    for (int index = 0; index < prepareSQL.getParams().length; index++)
    {
      redefinedParams[redefinedParamIndex++] = prepareSQL.getParams()[index];
    }
    for (int index = 0; index < countQuestionMarkInEndSql; index++)
    {
      redefinedParams[redefinedParamIndex++] = params[countQuestionMarkInFrontSql + index];
    }

    this.sql = redefinedSql;
    this.params = redefinedParams;
  }

  @Override
  public String toString()
  {
    return sql;
  }
}
